<template>
  <base-table-layout
    title="育苗点管理"
    :total="total"
    :current-page="currentPage"
    :page-size="pageSize"
    @update:currentPage="val => currentPage = val"
    @update:pageSize="val => pageSize = val"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <el-input
        v-model="searchForm.name"
        placeholder="育苗点名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleSearch"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >搜索</el-button>
      <el-button
        class="filter-item"
        type="info"
        icon="el-icon-refresh"
        @click="resetSearch"
      >重置</el-button>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <el-button
        type="success"
        icon="el-icon-plus"
        @click="handleAdd"
      >新增</el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="deptName" label="育苗点名称" width="200" />
        <el-table-column prop="address" label="详细地址" />
        <el-table-column prop="altitude" label="海拔高度" width="120">
          <template slot-scope="scope">
            {{ scope.row.altitude ? `${scope.row.altitude}米` : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="负责人" width="180">
          <template slot-scope="scope">
            <template v-if="scope.row.managerInfo">
              <el-button type="text" @click="handleBindManager(scope.row)">
                {{ scope.row.managerInfo.employeeName }}
              </el-button>
              <el-button 
                type="text" 
                style="margin-left: 10px; color: #F56C6C;" 
                @click="handleUnbindManager(scope.row)">
                <i class="el-icon-close"></i>
              </el-button>
            </template>
            <el-button v-else size="mini" type="primary" @click="handleBindManager(scope.row)">绑定管理员</el-button>
          </template>
        </el-table-column>
        <el-table-column label="联系电话" width="120">
          <template slot-scope="scope">
            {{ scope.row.managerInfo ? scope.row.managerInfo.phone : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <!-- 新增/编辑育苗点对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
        <el-form :model="nurseryForm" :rules="rules" ref="nurseryForm" label-width="100px">
          <el-form-item label="育苗点名称" prop="deptName">
            <el-input v-model="nurseryForm.deptName"></el-input>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input
              v-model="nurseryForm.address"
              placeholder="编辑时可选择地址"
              readonly
              class="address-input"
              @click.native="handleAddressClick">
              <template slot="append">
                <el-button 
                  icon="el-icon-location" 
                  @click.stop="handleAddressClick"
                  :disabled="!nurseryForm.deptId">
                  选择位置
                </el-button>
              </template>
              <template slot="prepend">
                <i class="el-icon-map-location"></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="海拔高度" prop="altitude">
            <el-input-number 
              v-model="nurseryForm.altitude"
              :min="0"
              :max="5000"
              :precision="2"
              :step="100"
              controls-position="right">
            </el-input-number>
            <span class="unit">米</span>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 使用百度地图选择器组件 -->
      <baidu-map-picker
        :visible.sync="mapDialogVisible"
        title="选择育苗点位置"
        :initial-center="mapInitialCenter"
        :initial-zoom="12"
        :selected-location="{
          lng: nurseryForm.longitude,
          lat: nurseryForm.latitude,
          address: nurseryForm.address
        }"
        @confirm="handleLocationConfirm"
      />

      <!-- 员工选择对话框 -->
      <el-dialog 
        title="选择管理员" 
        :visible.sync="employeeDialogVisible" 
        width="50%"
        :destroy-on-close="true"
        @close="handleEmployeeDialogClose">
        <div class="search-bar">
          <el-form :inline="true" :model="employeeSearchForm">
            <el-form-item label="员工姓名">
              <el-input v-model="employeeSearchForm.name" placeholder="请输入员工姓名"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchEmployees">查询</el-button>
              <el-button @click="resetEmployeeSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-table :data="employeeList" border style="width: 100%">
          <el-table-column prop="employeeName" label="姓名" width="120" />
          <el-table-column prop="phone" label="联系电话" width="120" />
          <el-table-column prop="idCard" label="身份证号" />
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button 
                size="mini" 
                type="primary" 
                @click="confirmBindManager(scope.row)">
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            @size-change="handleEmployeeSizeChange"
            @current-change="handleEmployeeCurrentChange"
            :current-page="employeeCurrentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="employeePageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="employeeTotal">
          </el-pagination>
        </div>
      </el-dialog>
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import _ from 'lodash'
import BaiduMapPicker from '@/components/BaiduMapPicker.vue'
import BaseTableLayout from '@/components/BaseTableLayout.vue'

export default {
  name: 'NurseryView',
  components: {
    BaiduMapPicker,
    BaseTableLayout
  },
  data() {
    return {
      loading: false,
      searchForm: {
        name: ''
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      nurseryForm: {
        deptName: '',
        address: '',
        longitude: null,
        latitude: null,
        altitude: null
      },
      rules: {
        deptName: [
          {required: true, message: '请输入育苗点名称', trigger: 'blur'}
        ],
        address: [
          {required: false, message: '请输入详细地址', trigger: 'blur'}
        ],
        altitude: [
          {required: false, type: 'number', message: '请输入正确的海拔高度', trigger: 'blur'}
        ]
      },
      mapDialogVisible: false,
      mapInitialCenter: {
        lng: 100.129176,
        lat: 24.437121
      },
      employeeDialogVisible: false,
      employeeSearchForm: {
        name: ''
      },
      employeeList: [],
      employeeCurrentPage: 1,
      employeePageSize: 10,
      employeeTotal: 0,
      currentDept: null
    }
  },
  methods: {
    async handleLoadData() {
      try {
        this.loading = true
        const response = await request.get('/departments/page', {
          params: {
            current: this.currentPage,
            size: this.pageSize,
            deptName: this.searchForm.name || undefined,
            deptType: 4 // 育苗点类型
          }
        })
        
        if (response.records) {
          const deptIds = response.records.map(dept => dept.deptId)
          
          // 批量获取地理位置信息
          const locationResponse = await request.post('/department-locations/batch', deptIds)
          const locationMap = new Map(locationResponse.map(loc => [loc.deptId, loc]))
          
          // 批量获取管理员信息
          const managerIds = response.records.filter(dept => dept.managerId).map(dept => dept.managerId)
          let managerMap = new Map()
          if (managerIds.length > 0) {
            const managerResponse = await request.post('/employees/batch', managerIds)
            managerMap = new Map(managerResponse.map(manager => [manager.employeeId, manager]))
          }
          
          // 整合数据
          response.records.forEach(dept => {
            const location = locationMap.get(dept.deptId)
            if (location) {
              dept.address = location.address
              dept.longitude = location.longitude
              dept.latitude = location.latitude
              dept.altitude = location.altitude
            }
            
            if (dept.managerId) {
              dept.managerInfo = managerMap.get(dept.managerId)
            }
          })

          this.tableData = response.records
          this.total = response.total
        } else {
          throw new Error('获取数据格式不正确')
        }
      } catch (error) {
        console.error('加载育苗点数据失败:', error)
        this.$message.error('加载育苗点数据失败')
        this.tableData = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    handleSearch: _.debounce(async function () {
      this.currentPage = 1
      await this.handleLoadData()
    }, 300),

    resetSearch() {
      this.searchForm.name = ''
      this.handleSearch()
    },

    handleAdd() {
      this.dialogTitle = '新增育苗点'
      this.nurseryForm = {
        deptName: '',
        address: '',
        longitude: null,
        latitude: null,
        altitude: null
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogTitle = '编辑育苗点'
      this.nurseryForm = {
        ...row,
        deptId: row.deptId
      }
      this.dialogVisible = true
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该育苗点信息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 先检查是否可以删除
        const checkResult = await request.get(`/departments/check-delete/${row.deptId}`)
        if (!checkResult.canDelete) {
          this.$message.error(checkResult.message || '该育苗点不能删除')
          return
        }

        // 先删除地理位置信息
        await request.delete(`/department-locations/${row.deptId}`)
        // 再删除部门信息
        await request.delete(`/departments/${row.deptId}`)

        this.$message.success('删除成功')
        await this.handleLoadData()
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除')
        } else {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.handleLoadData()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.handleLoadData()
    },

    showMapDialog() {
      this.mapDialogVisible = true
    },

    handleLocationConfirm(location) {
      this.nurseryForm.address = location.address
      this.nurseryForm.longitude = location.longitude
      this.nurseryForm.latitude = location.latitude
      this.mapDialogVisible = false
    },

    async submitForm() {
      try {
        const valid = await this.$refs.nurseryForm.validate()
        if (!valid) return

        // 保存部门基本信息
        const formData = {
          ...this.nurseryForm,
          deptType: 4, // 育苗点类型
          parentId: 1  // 育苗点直接归属于总部
        }

        let deptId
        if (this.nurseryForm.deptId) {
          // 编辑模式
          await request.put('/departments', formData)
          deptId = this.nurseryForm.deptId
        } else {
          // 新增模式
          const response = await request.post('/departments', formData)
          deptId = response.data
        }

        // 保存地理位置信息
        if (this.nurseryForm.longitude && this.nurseryForm.latitude) {
          await request.post('/department-locations', {
            deptId: deptId,
            address: this.nurseryForm.address,
            longitude: this.nurseryForm.longitude,
            latitude: this.nurseryForm.latitude,
            altitude: this.nurseryForm.altitude || 0
          })
        }

        this.$message.success(this.nurseryForm.deptId ? '更新成功' : '添加成功')
        this.dialogVisible = false
        await this.handleLoadData()
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败，请稍后重试')
      }
    },

    handleBindManager(row) {
      this.currentDept = row
      this.employeeDialogVisible = true
      this.employeeSearchForm.name = ''
      this.employeeCurrentPage = 1
      this.employeePageSize = 10
      this.loadEmployees()
    },

    async loadEmployees() {
      try {
        const response = await request.get('/employees/page', {
          params: {
            current: this.employeeCurrentPage,
            size: this.employeePageSize,
            name: this.employeeSearchForm.name || undefined
          }
        })
        
        if (response.records) {
          this.employeeList = response.records
          this.employeeTotal = response.total
        } else {
          throw new Error('获取数据格式不正确')
        }
      } catch (error) {
        console.error('加载员工数据失败:', error)
        this.$message.error('加载员工数据失败')
        this.employeeList = []
        this.employeeTotal = 0
      }
    },

    searchEmployees() {
      this.employeeCurrentPage = 1
      this.loadEmployees()
    },

    resetEmployeeSearch() {
      this.employeeSearchForm.name = ''
      this.employeeCurrentPage = 1
      this.loadEmployees()
    },

    handleEmployeeSizeChange(val) {
      this.employeePageSize = val
      this.loadEmployees()
    },

    handleEmployeeCurrentChange(val) {
      this.employeeCurrentPage = val
      this.loadEmployees()
    },

    async confirmBindManager(employee) {
      try {
        await request.put('/departments', {
          deptId: this.currentDept.deptId,
          managerId: employee.employeeId,
          deptType: 4,
          parentId: 1,
          deptName: this.currentDept.deptName
        })

        this.$message.success('绑定管理员成功')
        this.employeeDialogVisible = false
        await this.handleLoadData()
      } catch (error) {
        console.error('绑定管理员失败:', error)
        this.$message.error('绑定管理员失败')
      }
    },

    handleEmployeeDialogClose() {
      this.employeeSearchForm.name = ''
      this.employeeCurrentPage = 1
      this.employeePageSize = 10
      this.employeeList = []
      this.employeeTotal = 0
      this.currentDept = null
    },

    handleAddressClick() {
      if (!this.nurseryForm.deptId) {
        this.$message.info('请先保存育苗点基本信息后再选择地址')
        return
      }
      this.showMapDialog()
    },

    async handleUnbindManager(row) {
      try {
        await this.$confirm('确认取消绑定该负责人吗？', '提示', {
          type: 'warning'
        })
        
        await request.put(`/departments/${row.deptId}/unbind-manager`)

        this.$message.success('取消绑定成功')
        await this.handleLoadData()
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消操作')
        } else {
          console.error('取消绑定失败:', error)
          this.$message.error('取消绑定失败')
        }
      }
    }
  },
  created() {
    this.handleLoadData()
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.unit {
  margin-left: 10px;
  color: #606266;
}

.address-input {
  cursor: pointer;

  :deep(.el-input-group__prepend) {
    background-color: #f5f7fa;
  }

  :deep(.el-input__inner) {
    cursor: pointer;
    background-color: #fff;
  }

  :deep(.el-input-group__append) {
    background-color: #409EFF;
    border-color: #409EFF;
    color: #fff;
    cursor: pointer;

    &:hover {
      background-color: #66b1ff;
      border-color: #66b1ff;
    }

    .el-button {
      color: #fff;
      border: none;
      background: transparent;
      padding: 0;

      &:hover {
        color: #fff;
      }
    }
  }
}

.search-bar {
  margin-bottom: 20px;
}
</style>
